<script setup>
import * as echarts from 'echarts/core'
import {
  ToolboxComponent,
  TooltipComponent,
  TitleComponent,
  GridComponent,
  GraphicComponent,
  LegendComponent
} from 'echarts/components'
import { BarChart, LineChart, PieChart } from 'echarts/charts'
import { UniversalTransition } from 'echarts/features'
import { CanvasRenderer } from 'echarts/renderers'
import { onMounted, ref, computed, watch, nextTick } from 'vue'
import { propTypes } from '@/utils/propTypes'
import { getTableList } from '@/api/basic'
import { getOptions } from '@/utils/echarts'
import request from '@/config/axios/service'
import { EventSourcePolyfill } from 'event-source-polyfill'
import { useCache } from '@/hooks/web/useCache'

const { wsCache } = useCache()

echarts.use([
  ToolboxComponent,
  TooltipComponent,
  TitleComponent,
  GridComponent,
  GraphicComponent,
  LegendComponent,
  BarChart,
  LineChart,
  PieChart,
  CanvasRenderer,
  UniversalTransition
])

const color = ['#2f7cf1', '#89cf49', '#8d64f1']

const domRef = ref([])

// 获取饼图配置
const getPieOptions = (item) => {
  const data = item.data.map((d) => ({
    ...d,
    value: d.num
  }))
  const total = data.reduce((sum, item) => sum + item.value, 0)
  return {
    color,
    title: {
      text: item.name,
      left: 'left',
      subtext: item.lable || undefined
    },
    tooltip: {
      trigger: 'item',
      formatter: function (params) {
        return `${params.name}<br/>${params.value}(${params.data?.percent || params.percent + '%'})`
      }
    },
    // legend: {
    //   orient: 'vertical',
    //   left: 'right'
    // },
    series: [
      {
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 5
        },
        data: data,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        label: {
          formatter: function (params) {
            return `${params.name}\n${params.value}(${
              params.data?.percent || params.percent + '%'
            })`
          }
        }
      }
    ],
    graphic: {
      type: 'text',
      left: 'center',
      top: 'center',
      style: {
        text: `${item.totalTitle}\n${total}`,
        textAlign: 'center',
        fill: '#000',
        fontSize: 16,
        fontWeight: 'bold'
      }
    }
  }
}
// 获取折线图配置
const getLineOptions = (item) => {
  const legend = {
    left: 'right',
    data: item.data.map((d) => d.screenName)
  }
  const xAxisData = Object.keys(item.data[0].data)
  const series = item.data.map((d, i) => ({
    name: d.screenName,
    data: Object.values(d.data),
    type: 'line',
    areaStyle: {},
    smooth: true,
    emphasis: {
      focus: 'series'
    }
  }))
  return {
    title: {
      text: item.name,
      left: 'left',
      subtext: item.lable || undefined
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: xAxisData
    },
    legend,
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      }
    },
    yAxis: [
      {
        type: 'value'
      }
    ],
    series
  }
}

const dataList = ref([])
const totalTitles = ['报警次数', '异常风口数量', '摄像头总数', '报警次数', '异常风口数量']
const getData = async () => {
  return request({
    url: '/api/home_page_view',
    method: 'get'
  }).then((res) => {
    dataList.value = res.data.map((item, i) => ({ ...item, totalTitle: totalTitles[i] }))
    nextTick(() => {
      initEcharts()
    })
  })
}

// 初始化echarts
const initEcharts = () => {
  dataList.value.forEach((item, i) => {
    const chartDom = domRef.value[i]
    const echartInstance = echarts.init(chartDom)
    if (item.type === 'pie') {
      echartInstance.setOption(getPieOptions(item))
    } else if (item.type === 'line') {
      echartInstance.setOption(getLineOptions(item))
    }
  })
}

const noticeList = ref([])

const initNotice = () => {
  var source = new EventSourcePolyfill('/api/events', {
    headers: {
      token: wsCache.get('Admin-Token')
    }
  })
  source.addEventListener(
    'message',
    function (event) {
      var data = event.data
      if (typeof data === 'string') {
        try {
          data = JSON.parse(data)
        } catch (e) {}
      }
      noticeList.value.unshift(data)
    },
    false
  )
}

initNotice()

onMounted(async () => {
  setInterval(() => {
    getData()
  }, 10000)
  await getData()
})
</script>
<template>
  <div class="echarts-main">
    <div
      class="rev-card el-card el-card__body"
      :style="`grid-area: a${i + 1}`"
      v-for="(item, i) in dataList"
      :key="i"
    >
      <div class="echarts-container" ref="domRef"></div>
    </div>
    <div class="notice rev-card el-card el-card__body">
      <div class="text-18px font-bold">消息与通知</div>
      <div class="notice-list">
        <el-scrollbar>
          <div class="notice-item" v-for="(item, idx) in noticeList" :key="idx">{{
            item?.message
          }}</div>
        </el-scrollbar>
      </div>
    </div>
  </div>
</template>
<style lang="less" scoped>
.echarts-main {
  position: relative;
  box-sizing: border-box;
  padding: 15px;
  width: 100%;
  height: 100%;
  display: grid;
  grid-template-columns: 1.2fr 1.2fr 1.2fr 1fr;
  grid-template-rows: 380px 380px;
  grid-gap: 15px;
  grid-template-areas:
    'a1 a2 a3 b'
    'a4 a5 a6 a6';

  .echarts-container {
    width: 100%;
    min-height: 350px;
  }

  .notice {
    grid-area: b;
    display: flex;
    flex-direction: column;

    .notice-list {
      flex: 1;
      overflow: hidden;
      font-size: 14px;
      margin-top: 10px;
    }
  }
}
</style>
